import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Radio, message, Upload } from 'antd';
import { set } from "../../services/admin"
import { useSelector, useDispatch } from 'react-redux';
import { isModalVisible } from '../../store/slice/adminSlice';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { url } from '../../services';

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};

const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }

    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }

    return isJpgOrPng && isLt2M;
};


const Set = ({ setId, show }) => {

    const [form] = Form.useForm();

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();

    let count = useSelector((state) => state.admin.isModalVisible);
    let student = useSelector((state => state.admin.student))
    let dispatch = useDispatch()

    useEffect(() => {
        console.log(student);
        setImageUrl(`${url}/images/${student.headImg}`)
        form.setFieldsValue(student) //设置表单初始值
    }, [student._id])

    const handleOk = async () => {
        let values = form.getFieldsValue(); //获取表单值
        // console.log(values.headImg.file.response.filename);
        console.log(values);
        await set({ ...values, id: student._id });
        show();
        dispatch(isModalVisible(false))
    };

    const handleCancel = () => {
        dispatch(isModalVisible(false))
    };



    // const handleChange = (info) => {


    //     if (info.file.status === 'uploading') {
    //         setLoading(true);
    //         return;
    //     }

    //     if (info.file.status === 'done') {
    //         form.setFieldsValue({ ...form.getFieldsValue(), headImg: info.file.response.filename });
    //         // Get this url from response in real world.
    //         getBase64(info.file.originFileObj, (url) => {
    //             setLoading(false);
    //             setImageUrl(url);
    //         });
    //     }
    // };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );

    return (
        <>
            <Modal title="修改管理员信息" visible={count} onOk={handleOk} onCancel={handleCancel}>
                <Form
                    form={form}
                    name="addFrom"
                    className="login-form"
                    initialValues={{
                        remember: true,
                    }}
                >
                    {/* <Form.Item
                        name="headImg"
                        label="头像"
                        rules={[
                            {
                                required: true,
                            }
                        ]}
                    >
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action={url + "/upload"}
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? (
                                <img
                                    src={imageUrl}
                                    alt="avatar"
                                    style={{
                                        width: '100%',
                                    }}
                                />
                            ) : (
                                uploadButton
                            )}
                        </Upload>
                    </Form.Item> */}

                    <Form.Item
                        name="username"
                        label="账号"
                        rules={[
                            {
                                required: true,
                                message: '请输入管理员账号!',
                            }
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        name="pwd"
                        label="密码"
                        rules={[
                            {
                                required: true,
                                message: '请输入密码!',

                            }
                        ]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item
                        name="gender"
                        label="性别"
                        rules={[
                            {
                                required: true,
                                message: '请选择性别!',

                            }
                        ]}
                    >
                        <Radio.Group>
                            <Radio value="男">男</Radio>
                            <Radio value="女">女</Radio>
                        </Radio.Group>
                    </Form.Item>


                </Form>
            </Modal>
        </>
    );
};

export default Set;

// import React, { useState } from 'react'
// import InputElement from "../InputElement"
// import RadioElement from "../RadioElement"
// import { add } from '../../services/students'
// export default function Add(props) {
//     let [name, setname] = useState('');
//     let [age, setage] = useState('');
//     let [gender, setgender] = useState('');

//     const handleSubmit = async () => {
//         await add({ name, age, gender });
//         props.show();
//         setname("");
//         setage("");
//         setgender("");
//     };

//     return (
//         <div>
//             <h1>添加学生</h1>
//             <InputElement onInput={(e) => setname(e.target.value)} value={name} >姓名 : </InputElement>
//             <InputElement onInput={(e) => setage(e.target.value)} value={age} >年龄 : </InputElement>
//             <RadioElement
//                 onChange={(e) => setgender(e.target.value)}
//                 value={gender}
//                 name="gender">性别 : </RadioElement>
//             <button onClick={handleSubmit}> 确认增加</button>
//         </div >
//     )
// }





// import React from 'react'
// import InputElement from "../InputElement"
// import RadioElement from "../RadioElement"
// import { set } from "../../services/students"
// export default function Set(props) {

//     const handleSubmit = async () => {
//         let res = await set({ data: { ...props.student }, id: props.setId });
//         props.show();
//         console.log(res);
//     };

//     return (
//         <div>
//             <h1>修改学生</h1>
//             <InputElement
//                 onInput={(e) => { props.setStudent({ ...props.student, name: e.target.value }) }}
//                 value={props.student.name} >
//                 姓名 : </InputElement>

//             <InputElement
//                 onInput={(e) => { props.setStudent({ ...props.student, age: e.target.value }) }}
//                 value={props.student.age} >
//                 年龄 : </InputElement>

//             <RadioElement
//                 onChange={(e) => { props.setStudent({ ...props.student, gender: e.target.value }) }}
//                 value={props.student.gender} name="gender2" >
//                 性别 : </RadioElement>
//             <button onClick={handleSubmit} >确认修改</button>
//         </div>
//     )
// }
